<template>
  <!--要显示主体内容-->
  <div class="main">
    <div class="login">
      <div class="logo">
        <img src="../assets/my_logo.png" alt="">
      </div>
      <el-form :model="user" class="user_form" :rules="userRules" ref="userFormRef">
        <el-form-item prop="name">
          <el-input v-model="user.name" placeholder="邮箱" :prefix-icon="User" />
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input v-model="user.pwd" placeholder="密码" :prefix-icon="Lock" show-password />
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="submitForm(userFormRef)">登录</el-button>
          <el-button type="primary" @click="registration()">注册</el-button>
          <el-button type="success" @click="resetForm()">重置密码</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>


<script setup>
import { reactive, ref } from 'vue'
import { Lock, User } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'  // 引入路由
import api from '@/api/index.js'    // 导入api接口

const router = useRouter() // 创建路由对象
// 定义表单数据
const user = reactive({
  name: '',
  pwd: ''
})
// 定义表单规则
const userRules = reactive({
  name: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱地址', trigger: "blur" }
  ],
  pwd: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
  ]
})

// 定义表单ref
const userFormRef = ref(null)
// 定义重置表单的方法
const resetForm = () => {
  router.push('/reset_pwd')
}
// 定义登录功能
const submitForm = (formRef) => {
  formRef.validate((valid) => {
    if (valid) {
      api.getLogin(user).then(res => {
        console.log(res)
        // 根据后台返回的数据，做出不同的处理
        if (res.status == 200) {
          console.log(res.data)
          if (res.data.id == null) {
            ElMessage.error(res.data.msg)
          }
          else {
            // 登录成功
            ElMessage({
              message: res.data.name + "登录成功",
              type: 'success',
            })
            sessionStorage.setItem('token', res.data.token)
            // 跳转到主页
            router.push('/whelcome')
          }
        }
      })
    }
  })
}
// 定义注册功能
const registration = () => {
  router.push('/registration')
  console.log('跳转到注册页面')
}

</script>


<style scoped>
.main {
  width: 100%;
  height: 100%;
  background-color: rgb(233, 188, 8);
  display: flex;
  justify-content: center;
  align-items: center;
}


.login {
  width: 450px;
  height: 300px;
  background-color: white;
  border-radius: 5px;
}


.logo {
  width: 200px;
  border: 1px solid #eee;
  margin: 0 auto;
  margin-top: -65px;
  padding: 5px;
  border-radius: 5px;
  box-shadow: 0 0 10px #ddd;
}


img {
  width: 100%;
  height: 100%;
}


.user_form {
  padding: 50px;
}


.btns {
  display: flex;
  justify-content: space-between;
}


.btns button {
  flex: 1;
}
</style>